<template>
  <div id="oj-content">
    <div class="container">
      <div class="bank-container">
        <div class="left-list">
          <div class="filter-select">
            <div
              class="items"
              :style="{ height: !filterSource ? '40px' : 'auto' }"
            >
              <div class="category">来源</div>
              <div
                class="item"
                :class="selectSourceNum == index ? 'active' : ''"
                v-for="(item, index) of REMOTE_OJ"
                :key="index"
                @click="selectSource(item.key, index)"
              >
                <span :title="item.sourceName">{{ item.name }}</span
                ><span>{{ item.problemSum }}</span>
              </div>
              <div class="action" @click="openSource">
                {{ filterSource ? '收起' : '展开' }}
                <span
                  :style="{
                    display: 'inline-block',
                    transform: !filterSource ? 'rotate(180deg)' : '',
                  }"
                >
                  <i class="iconfont icon-arrow-up"></i>
                </span>
              </div>
            </div>
          </div>
          <div class="filter-select">
            <div
              class="items"
              :style="{ height: !filterKnowledge ? '92px' : 'auto' }"
            >
              <div class="category">标签</div>
              <div
                class="item"
                :class="selectTagNum == index ? 'active' : ''"
                v-for="(item, index) of tagList"
                :key="index"
                @click="selectTag(item.id, index)"
              >
                <span :title="item.tagName">{{ item.name }}</span
                ><span>{{ item.problemSum }}</span>
              </div>
              <div class="action" @click="openKnowledge">
                {{ filterKnowledge ? '收起' : '展开' }}
                <span
                  :style="{
                    display: 'inline-block',
                    transform: !filterKnowledge ? 'rotate(180deg)' : '',
                  }"
                >
                  <i class="iconfont icon-arrow-up"></i>
                </span>
              </div>
            </div>
          </div>
          <div class="filter-input">
            <div class="select-box">
              <el-select
                v-model="selectVal"
                placeholder="难度"
                size="small"
                @change="selectDifficulty"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="input-box">
              <el-input
                size="small"
                v-model="inputVal"
                placeholder="请输入题目名称搜索"
                suffix-icon="el-icon-search"
                @input="searchName"
              ></el-input>
            </div>
          </div>
          <div class="title">
            <div class="title-left">
              <span class="subject">题目</span>
            </div>
            <div class="title-right">
              <div data-sort="difficulty" class="title-item">
                <span>难度</span>
                <img
                  :src="diffArrow"
                  :title="diffTip"
                  @click="resort('difficulty')"
                />
              </div>
              <div data-sort="pass_rate" class="title-item">
                <span>通过率</span>
                <img
                  src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/question-icon.aba19e3.png"
                  title="通过率=通过人数/总提交人数"
                  width="20"
                  class="question-icon"
                />
                <img
                  :src="passArrow"
                  :title="passTip"
                  @click="resort('passRate')"
                />
              </div>
              <div data-sort="students_count" class="title-item">
                <span>挑战人数</span>
                <img
                  :src="challengeArrow"
                  :title="challengeTip"
                  @click="resort('challengeSum')"
                />
              </div>
            </div>
          </div>
          <div
            v-loading="problemLoading"
            class="problem-list"
            v-if="problemList && problemList.length > 0"
          >
            <div
              class="problem-item-wrapper"
              v-for="(item, index) of problemList"
              :key="index"
            >
              <div class="problem">
                <div class="problem-left">
                  <div class="problem-title">
                    <template v-if="isGetStatusOk">
                      <span
                        :title="JUDGE_STATUS[item.myStatus]['name']"
                        class="check-flag"
                        v-if="item.myStatus == 0"
                      >
                        <i
                          class="el-icon-check"
                          :style="getIconColor(item.myStatus)"
                        ></i>
                      </span>
                      <span
                        :title="JUDGE_STATUS[item.myStatus]['name']"
                        class="check-flag"
                        v-else-if="item.myStatus != -10"
                      >
                        <i
                          class="el-icon-minus"
                          :style="getIconColor(item.myStatus)"
                        ></i>
                      </span>
                      <span class="check-flag" v-else></span>
                    </template>
                    <span :title="item.title" class="name">
                      {{ item.title }}
                    </span>
                  </div>
                </div>
                <div class="problem-right">
                  <div class="problem-level">
                    <span
                      class="meta meta-level"
                      :class="item.difficulty | difficultyStr"
                    >
                      {{ item.difficulty | difficultyText }}
                    </span>
                  </div>
                  <div class="problem-passing">
                    <span class="meta meta-percent">
                      {{
                        item.total != 0
                          ? ((item.ac / item.total) * 100).toFixed(2)
                          : 0.0
                      }}%
                    </span>
                  </div>
                  <div class="problem-challenges">
                    <span class="meta meta-users">
                      {{ item.challengeSum }}
                    </span>
                  </div>
                </div>
                <div class="wrapper">
                  <button
                    type="button"
                    class="btn btn-primary btn-sm"
                    @click="startChallenge(item.problemId)"
                  >
                    开始挑战
                  </button>
                </div>
              </div>
              <div class="problem-tags">
                <span
                  :title="tag.name"
                  class="tag"
                  v-for="(tag, index) of item.tags"
                  :key="index"
                >
                  {{ tag.name }}
                </span>
              </div>
            </div>
            <div class="page-bar">
              <Pagination
                :total="total"
                :page-size="limit"
                @on-change="onPageChange"
                :current.sync="query.currentPage"
                :layout="'prev, pager, next'"
              ></Pagination>
            </div>
          </div>
          <el-empty v-else :description="'暂无数据'"></el-empty>
        </div>

        <div class="right-rank" v-if="rankDetail">
          <div class="panel-wrap">
            <div class="top">
              <span class="rank-name">个人练习榜</span>
              <div class="tabs-wrap">
                <div
                  class="tab first"
                  :class="rankTab ? 'tab-select' : ''"
                  @click="rankTabClick(true)"
                >
                  本周
                </div>
                <div
                  class="tab last"
                  :class="!rankTab ? 'tab-select' : ''"
                  @click="rankTabClick(false)"
                >
                  总榜
                </div>
              </div>
            </div>
            <div class="middle">
              <div class="inner-wrap">
                <div class="inegral-statistic-wrap">
                  <!-- <div class="key-value-wrap first">
                    <span class="key">我已完成</span>
                    <div class="value">
                      <span class="rank-val">{{ rankDetail.recordSum }}题</span>
                    </div>
                  </div>
                  <div class="rank">No.{{ rankDetail.myRanking }}</div> -->
                </div>
              </div>
            </div>
            <div class="bottom" v-loading="rankLoading">
              <div
                class="personal-rank-item"
                v-for="(item, index) of recentUserACRecord"
                :key="index"
              >
                <div class="left">
                  <div class="rank-wrap small">
                    <div class="first" v-if="index < 3">
                      <img :src="rankStarImgs[index]" />
                    </div>
                    <span class="text" v-else>{{ index + 1 }}</span>
                  </div>
                  <div class="unit-info-wrap">
                    <div class="avatar">
                      <div
                        class="user-avatar user-avatar-link inline-block"
                        style="width: 40px; height: 40px"
                      >
                        <!-- <img
                          src="https://static-qiniu.lanqiao.cn/avatar/uid3478370-20220704-1656899490009?imageView2/1/w/40/h/40/"
                          class="user-avatar-image"
                        /> -->
                        <avatar
                          :username="item.username"
                          :inline="true"
                          :size="40"
                          color="#FFF"
                          :src="item.avatar"
                          class="user-avatar"
                        ></avatar>
                        <div class="vip-icon-container"></div>
                      </div>
                    </div>
                    <div class="unit">
                      <div :title="item.name" class="name">
                        {{ item.username }}
                      </div>
                      <div title="--" class="extra">{{ item.username }}</div>
                    </div>
                  </div>
                </div>
                <div class="score">{{ item.ac }}题</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// import { getSource, getTags, getProblems, problemRank } from '@/api/api'
import api from '@/common/api'
import {
  PROBLEM_LEVEL,
  JUDGE_STATUS,
  JUDGE_STATUS_RESERVE,
  REMOTE_OJ,
} from '@/common/constants'
import utils from '@/common/utils'
import 'element-ui/lib/theme-chalk/display.css'
import Pagination from '@/components/oj/common/Pagination'
import Avatar from 'vue-avatar'

export default {
  name: 'ProblemList-New',
  components: {
    Pagination,
    Avatar,
  },
  data() {
    return {
      PROBLEM_LEVEL: {},
      JUDGE_STATUS: {},
      JUDGE_STATUS_RESERVE: {},
      REMOTE_OJ: {},
      limit: 5,
      total: 0,
      problemList: [],
      rankStarImgs: [
        'https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-1-small.61012f1.png',
        'https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-2.b7a14ad.png',
        'https://static.shiyanlou.com/lanqiao/frontend/dist/img/p-medal-3.0ce2247.png',
      ],
      rankList: [],
      rankDetail: {},
      recentUserACRecord: [],
      options: [
        {
          value: 0,
          label: '简单',
        },
        {
          value: 1,
          label: '中等',
        },
        {
          value: 2,
          label: '困难',
        },
      ],
      selectVal: '',
      inputVal: '',
      sourceList: [],
      tagList: [],
      query: {
        keyword: '',
        difficulty: '',
        oj: '',
        tagId: '',
        currentPage: 1,
      },
      filterSource: false,
      filterKnowledge: false,
      selectSourceNum: 0,
      selectTagNum: 0,
      recordSortStr: '',
      sameSortCount: 0,
      rankTab: true,
      rankLoading: false,
      problemLoading: false,
      isGetStatusOk: false,
      arrowIcons: [
        '',
        '',
        '',
      ],
    }
  },
  computed: {
    ...mapGetters(['isAuthenticated']),
    diffArrow() {
      let iconStr
      switch (this.query.problemSort) {
        case 'difficultyAsc':
          iconStr = this.arrowIcons[1]
          break
        case 'difficultyDesc':
          iconStr = this.arrowIcons[2]
          break
        default:
          iconStr = this.arrowIcons[0]
      }
      return iconStr
    },
    diffTip() {
      let tipStr
      switch (this.query.problemSort) {
        case 'difficultyAsc':
          tipStr = '由简单到困难'
          break
        case 'difficultyDesc':
          tipStr = '由困难到简单'
          break
        default:
          tipStr = ''
      }
      return tipStr
    },
    passArrow() {
      let iconStr
      switch (this.query.problemSort) {
        case 'passRateAsc':
          iconStr = this.arrowIcons[1]
          break
        case 'passRateDesc':
          iconStr = this.arrowIcons[2]
          break
        default:
          iconStr = this.arrowIcons[0]
      }
      return iconStr
    },
    passTip() {
      let tipStr
      switch (this.query.problemSort) {
        case 'passRateAsc':
          tipStr = '由低到高'
          break
        case 'passRateDesc':
          tipStr = '由高到低'
          break
        default:
          tipStr = ''
      }
      return tipStr
    },
    challengeArrow() {
      let iconStr
      switch (this.query.problemSort) {
        case 'challengeSumAsc':
          iconStr = this.arrowIcons[1]
          break
        case 'challengeSumDesc':
          iconStr = this.arrowIcons[2]
          break
        default:
          iconStr = this.arrowIcons[0]
      }
      return iconStr
    },
    challengeTip() {
      let tipStr
      switch (this.query.problemSort) {
        case 'challengeSumAsc':
          tipStr = '由少到多'
          break
        case 'challengeSumDesc':
          tipStr = '由多到少'
          break
        default:
          tipStr = ''
      }
      return tipStr
    },
  },
  mounted() {
    // 获取筛选项
    this.REMOTE_OJ = Object.assign({}, REMOTE_OJ)
    this.JUDGE_STATUS = Object.assign({}, JUDGE_STATUS)
    this.getTagList('ALL')
    // 获取题目列表
    this.getProblemList()
    // 获取排行榜
    this.getProblemRank(7)
  },
  methods: {
    openSource() {
      this.filterSource = !this.filterSource
    },
    openKnowledge() {
      this.filterKnowledge = !this.filterKnowledge
    },
    getTagList(oj) {
      if (oj == 'Mine') {
        oj = 'ME'
      }
      api.getProblemTagList(oj).then(
        (res) => {
          this.tagList = res.data.data
          this.tagList.unshift({
            name: '全部',
            oj: 'ALL',
          })
        },
        (res) => {
          this.loadings.tag = false
        }
      )
    },
    getProblemList() {
      let queryParams = Object.assign({}, this.query)
      this.problemLoading = true
      api.getProblemList(this.limit, queryParams).then(
        (res) => {
          this.total = res.data.data.total
          this.problemList = res.data.data.records
          this.problemLoading = false
          if (this.isAuthenticated) {
            // 如果已登录，则需要查询对当前页面题目列表中各个题目的提交情况
            let pidList = []
            for (let index = 0; index < this.problemList.length; index++) {
              pidList.push(this.problemList[index].pid)
            }
            if (pidList.length > 0) {
              // 必须当前页有显示题目才发送查询请求
              this.isGetStatusOk = false
              let isContestProblemList = false // 为了与比赛题目区分
              api
                .getUserProblemStatus(pidList, isContestProblemList)
                .then((res) => {
                  let result = res.data.data
                  for (
                    let index = 0;
                    index < this.problemList.length;
                    index++
                  ) {
                    this.problemList[index]['myStatus'] =
                      result[this.problemList[index].pid].status
                  }
                  this.isGetStatusOk = true
                })
            }
          }
        },
        (res) => {
          this.problemLoading = false
        }
      )
    },
    onPageChange(num) {
      this.query.currentPage = num
      this.getProblemList()
    },
    getProblemRank(date) {
      this.rankLoading = true
      api.getRecent7ACRank().then(
        (res) => {
          this.recentUserACRecord = res.data.data
          this.rankLoading = false
        },
        (err) => {
          this.rankLoading = false
        }
      )
    },
    startChallenge(id) {
      this.$router.push({
        path: '/problem/' + id,
      })
    },
    searchName(val) {
      this.query.keyword = val
      this.getProblemList()
    },
    selectSource(id, num) {
      this.selectSourceNum = num
      this.query.oj = id
      this.getProblemList()
    },
    selectTag(id, num) {
      this.selectTagNum = num
      this.query.tagId = id
      this.getProblemList()
    },
    selectDifficulty(val) {
      this.query.difficulty = val
      this.getProblemList()
    },
    rankTabClick(flag) {
      this.rankTab = flag
      this.rankTab ? this.getProblemRank(7) : this.getProblemRank('')
    },
    resort(flag) {
      if (this.recordSortStr) {
        if (this.recordSortStr == flag) {
          if (this.sameSortCount == 1) {
            this.sameSortCount = 2
            this.query.problemSort = flag + 'Desc'
          } else if (this.sameSortCount == 2) {
            this.sameSortCount = 3
            this.query.problemSort = ''
          } else if (this.sameSortCount == 3) {
            this.query.problemSort = flag + 'Asc'
            this.sameSortCount = 1
          }
        } else {
          this.query.problemSort = flag + 'Asc'
          this.sameSortCount = 1
          this.recordSortStr = flag
        }
      } else {
        this.query.problemSort = flag + 'Asc'
        this.recordSortStr = flag
        this.sameSortCount = 1
      }
      this.getProblemList()
    },
    getIconColor(status) {
      if (status || status == 0)
        return (
          'font-weight: 600;font-size: 16px;color:' +
          this.JUDGE_STATUS[status].rgb
        )
    },
  },
  watch: {
    $route(newVal, oldVal) {
      if (newVal) {
        this.getProblemRank(7)
      }
    },
    immediate: true,
    deep: true,
  },
  filters: {
    difficultyText(val) {
      let text = ''
      if (!val) return
      switch (val) {
        case 0:
          text = '简单'
          break
        case 1:
          text = '中等'
          break
        case 2:
          text = '困难'
          break
        default:
          return
      }
      return text
    },
    difficultyStr(val) {
      let str = ''
      if (!val) return
      switch (val) {
        case 0:
          str = 'simple'
          break
        case 1:
          str = 'middle'
          break
        case 2:
          str = 'hard'
          break
        default:
          return
      }
      return str
    },
    diffArrow(val) {
      let iconStr
      switch (val) {
        case 'difficultyAsc':
          iconStr = this.arrowIcons[1]
          break
        case 'difficultyDesc':
          iconStr = this.arrowIcons[2]
          break
        default:
          iconStr = this.arrowIcons[0]
      }
      return iconStr
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/question.scss';

.page-bar {
  margin-right: 30px;
}
</style>
